/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.iuhao.mongo;


import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;

import static java.util.Collections.singletonList;

/**
 *
 * @author Liu Jianwei<liujianwei@vcredit.com>
 * @date 2016-5-13
 */
@EnableConfigurationProperties({O2OMongoProperties.class})
public class O2OMongoConfiguration extends AbstractMongoConfiguration {

    private static final Logger logger = Logger.getLogger(O2OMongoConfiguration.class);

    @Autowired
    private O2OMongoProperties mongoProperties;

    @Override
    protected String getDatabaseName() {
        return mongoProperties.getDatabase();
    }

    @Override
    public Mongo mongo() throws Exception {
        logger.info("<========== Mongo DataSource ==========>:" + mongoProperties.getHost());
        if(mongoProperties.getUsername() != null && mongoProperties.getPassword() != null) {
            return new MongoClient(singletonList(new ServerAddress(mongoProperties.getHost(), mongoProperties.getPort())),
                singletonList(MongoCredential.createCredential(mongoProperties.getUsername(),mongoProperties.getDatabase(), mongoProperties.getPassword().toCharArray())));
        } else {
            return new MongoClient(singletonList(new ServerAddress(mongoProperties.getHost(), mongoProperties.getPort())));
        }
        
    }

}
